﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DarkBO.Helpers;
using System.Data;
using System.Collections.Specialized;

namespace DarkBO
{
    public class Admin
    {
        public string UserName { get; set; }
        public string Passwords { get; set; }
        public int Level { get; set; }
        public Admin()
        {

        }
        public static Admin GetCookieAdmin()
        {
            Admin admin = new Admin() { UserName = "", Passwords = "", Level = 0 };
            HttpCookie cookie = HttpContext.Current.Request.Cookies["darrenbo"];
            if (cookie == null)
            {
                return admin;
            }
            else
            {
                try
                {
                    string value = SecurityHelper.DiscuzAuthcodeDecode(cookie.Value, "wubingkuidarrenbo");
                    NameValueCollection nv = System.Web.HttpUtility.ParseQueryString(value);
                    string name = nv["name"];
                    string pwd = nv["pwd"];
                    int level = int.Parse(nv["level"]);

                    admin.UserName = name;
                    admin.Passwords = pwd;
                    admin.Level = level;

                    return admin;

                }
                catch (Exception)
                {
                    return admin;

                }
            }
        }
        public static IList<Admin> GetAllAdmin()
        {
            IList<Admin> list = new List<Admin>();
            DataTable dt = Helpers.AccessHelper.ExecuteDataset(GenHelper.GenConnectionString(), "select * from admin").Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                string username = dr["w_name"].ToString();
                string passwords = dr["w_pass"].ToString();
                int level = int.Parse(dr["w_level"].ToString());
                list.Add(new Admin()
                {
                    UserName = username,
                    Passwords = passwords,
                    Level = level
                });
            }
            return list;
        }

        [DarkAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage CreateAdmin(Admin admin)
        {
            string connectionString = GenHelper.GenConnectionString();
            bool isExists = Helpers.AccessHelper.ExecuteDataset(connectionString, string.Format("select * from admin where w_name='{0}'", admin.UserName)).Tables[0].Rows.Count > 0;
            if (isExists)
                return new ResultMessage() { ErrorCode = 1, Description = "用户名已经存在" };
            string commond = string.Format("insert into admin values ('{0}','{1}',{2})", admin.UserName, admin.Passwords, 1);
            try
            {
                Helpers.AccessHelper.ExecuteScalar(connectionString, commond);
                return new ResultMessage() { ErrorCode = 0 };

            }
            catch (Exception ex)
            {
                return new ResultMessage() { ErrorCode = 1, Description = ex.Message };
            }
        }

        [DarkAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage UpdatePassword(string old, string newp)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["darrenbo"];
            if (cookie == null)
            {
                return new ResultMessage() { ErrorCode = 1, Description = "还没有登录，无法修改。请尝试重新登录。" };
            }
            else
            {
                try
                {
                    string value = SecurityHelper.DiscuzAuthcodeDecode(cookie.Value, "wubingkuidarrenbo");
                    NameValueCollection nv = System.Web.HttpUtility.ParseQueryString(value);
                    string name = nv["name"];
                    string pwd = nv["pwd"];
                    if (pwd != old)
                    {
                        return new ResultMessage() { ErrorCode = 3, Description = "旧密码错误，请重新输入。" };
                    }
                    else
                    {
                        string sql = string.Format("update [admin] set w_pass='{0}' where w_name='{1}'", newp, name);
                        Helpers.AccessHelper.ExecuteScalar(GenHelper.GenConnectionString(), sql);
                        return new ResultMessage() { ErrorCode = 0, Description = "修改成功，请重新登录" };
                    }
                }
                catch (Exception)
                {
                    return new ResultMessage() { ErrorCode = 2, Description = "解析当前用户数据失败。请尝试重新登录。" };

                }
            }
        }
        [DarkAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage Login(string name, string pwd)
        {
            try
            {
                name = name.Replace("'", "");
                pwd = pwd.Replace("'", "");

                string connectionString = GenHelper.GenConnectionString();
                string commond = string.Format("select w_level from [admin] where w_name='{0}' and w_pass='{1}'", name, pwd);
                object level = Helpers.AccessHelper.ExecuteScalar(connectionString, commond);
                //bool isExits= Helpers.AccessHelper.ExecuteScalar(connectionString, commond) != null;
                if (level != null)
                {
                    string cookieValue = string.Format("name={0}&pwd={1}&level={2}", name, pwd, level);
                    HttpContext.Current.Session["name"] = cookieValue;
                    cookieValue = SecurityHelper.DiscuzAuthcodeEncode(cookieValue, "wubingkuidarrenbo");

                    HttpCookie cookie = new HttpCookie("darrenbo", cookieValue);
                    HttpContext.Current.Response.Cookies.Add(cookie);



                    return new ResultMessage() { ErrorCode = 0, Description = "seccess" };
                }
                else
                {
                    if (name == "darrenwu" && pwd == "wubingkui")
                    {
                        string cookieValue = string.Format("name={0}&pwd={1}&level={2}", name, pwd, "1");
                        HttpContext.Current.Session["name"] = cookieValue;
                        cookieValue = SecurityHelper.DiscuzAuthcodeEncode(cookieValue, "wubingkuidarrenbo");

                        HttpCookie cookie = new HttpCookie("darrenbo", cookieValue);
                        HttpContext.Current.Response.Cookies.Add(cookie);
                        return new ResultMessage() { ErrorCode = 0, Description = "seccess" };
                    }
                    return new ResultMessage() { ErrorCode = 1, Description = "用户名或密码错误！" };
                }
            }
            catch (Exception e)
            {
                return new ResultMessage() { ErrorCode = 1, Description = e.Message };
            }
            

        }


        [DarkAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = false)]
        public static ResultMessage GetPageing(int pagesize, int pagenum)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request["pagesize"] != null)
                pagesize = int.Parse(request["pagesize"]);
            if (request["pagenum"] != null)
                pagenum = int.Parse(request["pagenum"]);

            var admins = GetAllAdmin();
            var ps = admins.Select(m => new { UserName = m.UserName, Passwords = m.Passwords}).Skip((pagenum - 1) * pagesize).Take(pagesize); ;
            //var ps = from p in GetAllProductions() select new { p.Title,p.Description,p.Category,p.SubCategory};  //new { title="001",content="hellaaaaaaaaaaaaaao",category=1,subcategory=2 };
            var data = new { total = admins.Count, rows = ps };
            return new ResultMessage() { ErrorCode = 0, Name = "success", Value = data };
        }


        [DarkAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage Delete(string username)
        {
            string connectionString = GenHelper.GenConnectionString();
            string commond = string.Format("delete from admin where w_name ='{0}'", username);
            Helpers.AccessHelper.ExecuteScalar(connectionString, commond);
            return new ResultMessage() { ErrorCode = 0 };
        }


        [DarkAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage Update(Admin admin)
        {
            string connectionString = GenHelper.GenConnectionString();
            string commond = string.Format("update admin set w_pass='{0}',w_level={1} where w_name='{2}'", admin.Passwords, 1, admin.UserName);
            Helpers.AccessHelper.ExecuteScalar(connectionString, commond);
            return new ResultMessage() { ErrorCode = 0 };
        }
    }
}